Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的 __proto__ 。
1 | const person = { |
语法
Object.create(proto[, propertiesObject])
参数
proto
- 新创建对象的原型对象。
propertiesObject ({})
- 可选。如果没有指定为
undefined
,则是要添加到新创建对象的可枚举属性(即其自身定义的属性,而不是其原型链上的枚举属性)对象的属性描述符以及相应的属性名称。这些属性对应Object.defineProperties()
的第二个参数。返回值
- 一个新对象,带着指定的原型对象和属性。
兼容写法
1
2
3
4
5
6
7
8
9
10
11Object.create = Object.create || function ( proto ){
if (typeof proto !== 'object' && typeof proto !== 'function') {
throw new TypeError('Object prototype may only be an Object: ' + proto);
} else if (proto === null) {
throw new Error("This browser's implementation of Object.create is a shim and doesn't support 'null' as the first argument.");
}
function F () {}
F.prototype = proto;
return new F();
}
- 一个新对象,带着指定的原型对象和属性。
- 本文作者: 悲小剧
- 本文链接: https://htb58.github.io/2019/09/24/Object.create 详解/
- 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!